<template>
    <div>
        <!-- 操作日志详细 -->
        <el-dialog title="设备日志" :visible.sync="openDetail" width="90%" append-to-body>
            <!-- <el-form ref="form" :model="form" label-width="100px" size="mini">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="设备名称：">{{ form.deviceName }} </el-form-item>
                        <el-form-item label="设备地址：">{{ form.deviceAddr }} </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备imei：">{{ form.imei }}</el-form-item>
                        <el-form-item label="设备ID：">{{ form.deviceId }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="设备状态：">{{ form.deviceState }}</el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="创建时间：">{{ form.createTime }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注：">{{ form.remark }}</el-form-item>
                    </el-col>
                </el-row>
            </el-form> -->
            <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="设备参数日志" name="1"></el-tab-pane>
                <el-tab-pane label="设备报警日志" name="2"></el-tab-pane>
                <el-tab-pane label="设备水位日志" name="3"></el-tab-pane>
                <el-table v-loading="loading" :data="postList" height="90%" border>
                    ">
                    <el-table-column label="设备编号" align="center" prop="deviceId" />
                    <el-table-column label="设备imei" align="center" prop="imei" />
                    <template v-if="activeName === '1'">
                        <el-table-column label="日志详细" align="center" width="345" prop="deviceParameterLog">
                            <template slot-scope="scope">
                                <div class="alarm-log">
                                    <!-- 优先使用 deviceParameterLogList（含 name/value），没有则回退到 deviceParameterLogJson -->
                                    <template
                                        v-if="scope.row.deviceParameterLogList && scope.row.deviceParameterLogList.length">
                                        <div v-for="entry in scope.row.deviceParameterLogList" :key="entry.key"
                                            class="log-item">
                                            <div class="log-key-block">
                                                <span class="log-name">{{ entry.name }}</span>
                                                <span class="log-subkey">{{ entry.key }}</span>
                                            </div>
                                            <span class="log-value">{{ entry.value }}</span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        {{ scope.row.deviceParameterLog }}
                                    </template>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                    <template v-if="activeName === '2'">
                        <el-table-column label="日志详细" align="center" width="345" prop="deviceAlarmLog">
                            <template slot-scope="scope">
                                <div class="alarm-log">
                                    <!-- 优先使用 deviceAlarmLogList -->
                                    <template
                                        v-if="scope.row.deviceAlarmLogList && scope.row.deviceAlarmLogList.length">
                                        <div v-for="entry in scope.row.deviceAlarmLogList" :key="entry.key"
                                            class="log-item">
                                            <div class="log-key-block">
                                                <span class="log-name">{{ entry.name }}</span>
                                                <span class="log-subkey">{{ entry.key }}</span>
                                            </div>
                                            <span class="log-value">{{ entry.value }}</span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        {{ scope.row.deviceAlarmLog }}

                                    </template>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                    <template v-if="activeName === '3'">
                        <el-table-column label="日志详细" align="center" width="345" prop="deviceLevelLog">
                            <template slot-scope="scope">
                                <div class="alarm-log">
                                    <!-- 优先使用 deviceLevelLogList -->
                                    <template
                                        v-if="scope.row.deviceLevelLogList && scope.row.deviceLevelLogList.length">
                                        <div v-for="entry in scope.row.deviceLevelLogList" :key="entry.key"
                                            class="log-item">
                                            <div class="log-key-block">
                                                <span class="log-name">{{ entry.name }}</span>
                                                <span class="log-subkey">{{ entry.key }}</span>
                                            </div>
                                            <span class="log-value">{{ entry.value }}</span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        {{ scope.row.deviceLevelLog }}
                                    </template>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                    <el-table-column label="备注" align="center" prop="remark" />
                    <el-table-column label="创建时间" align="center" prop="createTime">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <!-- <el-button size="mini" type="text" icon="el-icon-date"
                                @click="handleViewLog(scope.row, scope.index)">对比</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
                <el-drawer title="参数对比" size="40%" :visible.sync="drawer" append-to-body direction="rtl">
                    <div v-if="compareInfo.before && Object.keys(compareInfo.before).length" class="param-compare">
                        <el-table :data="compareTable" border size="small" style="width: 100%">
                            <el-table-column label="参数名" width="160">
                                <template slot-scope="{ row }">
                                    <div class="param-name">
                                        <span>{{ row.name }}</span>
                                        <span class="param-key">{{ row.key }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="上一条数据" prop="before" />
                            <el-table-column label="当前数据" prop="now">
                                <template slot-scope="{ row }">
                                    <span :class="{ changed: row.changed }">{{ row.now }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div v-else class="empty">暂无数据</div>
                </el-drawer>
            </el-tabs>
            <div slot="footer" class="dialog-footer">
                <el-button @click="openDetail = false">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { paramLogListApi, alarmLogListApi, levelLogListApi, paramLogCompareApi, alarmLogCompareApi, levelLogCompareApi } from '@/api/index'
import { parseJSONSafe } from '@/utils/jsonUtil'
import uploadJson from './upload.json'
export default {
    name: "Post",
    data() {
        return {
            drawer: false,
            direction: 'rtl',
            activeName: '1',
            openDetail: false,
            form: {},
            total: 0,
            postList: [],
            loading: true,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                deviceId: undefined,
                orderByColumn: "create_time",
                isAsc: "desc"
            },
            compareInfo: {
                before: "",
                now: ""
            }
        }
    },
    computed: {
        title() {
            return this.activeName == '1' ? '设备参数日志' : this.activeName == '2' ? '设备运行日志' : '设备报警日志'
        },
        // 返回已解析的 before/now（总是对象），并添加参数名称映射
        parsedCompare() {
            const safeParse = (x) => {
                if (!x && x !== 0) return {}
                if (typeof x === 'object') return x
                if (typeof x === 'string') {
                    try {
                        // 把 \r\n 等转义显示去掉，然后解析
                        // 也兼容后端返回带外层引号的字符串
                        const cleaned = x.trim()
                        return JSON.parse(cleaned)
                    } catch (e) {
                        // 有时候字符串里是双个引号包裹的，再试一下去掉首尾引号
                        try {
                            const stripped = x.trim().replace(/^"(.*)"$/, '$1')
                            const unescaped = stripped.replace(/\r\n/g, '').replace(/\\"/g, '"')
                            return JSON.parse(unescaped)
                        } catch (e2) {
                            console.error('parsedCompare JSON.parse failed for:', x, e, e2)
                            return {}
                        }
                    }
                }
                return {}
            }

            // 把原始对象转换为带 name 的数组
            const objectToNamedArray = (obj) => {
                if (!obj || typeof obj !== 'object') return []
                return Object.keys(obj).map(key => ({
                    key,
                    value: obj[key],
                    name: uploadJson && uploadJson[key] && uploadJson[key].name ? uploadJson[key].name : key
                }))
            }

            const rawBefore = safeParse(this.compareInfo.before)
            const rawNow = safeParse(this.compareInfo.now)

            // 为 before 和 now 添加参数名映射
            return {
                before: objectToNamedArray(rawBefore),
                now: objectToNamedArray(rawNow)
            }
        },
        // 用于展示的表格数据
        compareTable() {
            const before = this.parsedCompare.before || []
            const now = this.parsedCompare.now || []

            // 合并 before 和 now 中的所有唯一 key
            const keys = Array.from(new Set([
                ...before.map(item => item.key),
                ...now.map(item => item.key)
            ]))

            const rows = keys.map(key => {
                const beforeItem = before.find(item => item.key === key) || {}
                const nowItem = now.find(item => item.key === key) || {}
                const changed = String(beforeItem.value) !== String(nowItem.value)

                return {
                    key,
                    name: nowItem.name || beforeItem.name || key, // 优先使用新值的 name
                    before: beforeItem.value,
                    now: nowItem.value,
                    changed
                }
            })

            return this.onlyChanged ? rows.filter(r => r.changed) : rows
        }
    },
    methods: {
        handleClose() {
            this.drawer = false;
        },
        /** 查询设备列表 */
        getList() {
            console.log(uploadJson, 'uploadJson');
            this.loading = true;
            let api
            if (this.activeName === '1') {
                api = paramLogListApi
            } else if (this.activeName === '2') {
                api = alarmLogListApi
            } else {
                api = levelLogListApi
            }
            api(this.queryParams).then(response => {
                console.log(response, 'response-日志列表');
                this.postList = response.rows
                this.total = response.total
                this.loading = false;
                if (response.rows.length > 0) {
                    response.rows.forEach(item => {
                        // 解析原始日志字段为对象（如果可能）
                        if (item.deviceParameterLog) {
                            const parsed = parseJSONSafe(item.deviceParameterLog)
                            console.log(parsed, '✅ 转成真正JSON对象')
                            item.deviceParameterLogJson = parsed || item.deviceParameterLog

                            // 把对象转换为数组并加上 name（从 uploadJson 映射），方便前端展示
                            if (typeof item.deviceParameterLogJson !== 'object' || !item.deviceParameterLogJson) {
                                item.deviceParameterLogList = []
                            } else {
                                try {
                                    const obj = item.deviceParameterLogJson
                                    item.deviceParameterLogList = Object.keys(obj).map(key => ({
                                        key,
                                        value: obj[key],
                                        // upload.json 的结构是 { key: { name: 'xxx', key: 'key' } }
                                        name: uploadJson && uploadJson[key] && uploadJson[key].name ? uploadJson[key].name : key
                                    }))
                                } catch (e) {
                                    item.deviceParameterLogList = []
                                }
                            }
                            console.log(item.deviceParameterLogList);
                        }

                        if (item.deviceAlarmLog) {
                            const parsed = parseJSONSafe(item.deviceAlarmLog)
                            console.log(parsed, '✅ 转成真正JSON对象')
                            item.deviceAlarmLogJson = parsed || item.deviceAlarmLog

                            if (typeof item.deviceAlarmLogJson !== 'object' || !item.deviceAlarmLogJson) {
                                item.deviceAlarmLogList = []
                            } else {
                                try {
                                    const obj = item.deviceAlarmLogJson
                                    item.deviceAlarmLogList = Object.keys(obj).map(key => ({
                                        key,
                                        value: obj[key],
                                        name: uploadJson && uploadJson[key] && uploadJson[key].name ? uploadJson[key].name : key
                                    }))
                                } catch (e) {
                                    item.deviceAlarmLogList = []
                                }
                            }
                            console.log(item.deviceAlarmLogList);

                        }

                        if (item.deviceLevelLog) {
                            const parsed = parseJSONSafe(item.deviceLevelLog)
                            console.log(parsed, '✅ 转成真正JSON对象')
                            item.deviceLevelLogJson = parsed || item.deviceLevelLog

                            if (typeof item.deviceLevelLogJson !== 'object' || !item.deviceLevelLogJson) {
                                item.deviceLevelLogList = []
                            } else {
                                try {
                                    const obj = item.deviceLevelLogJson
                                    item.deviceLevelLogList = Object.keys(obj).map(key => ({
                                        key,
                                        value: obj[key],
                                        name: uploadJson && uploadJson[key] && uploadJson[key].name ? uploadJson[key].name : key
                                    }))
                                } catch (e) {
                                    item.deviceLevelLogList = []
                                }
                            }
                            console.log(item.deviceLevelLogList);

                        }

                        // 合并成一个统一的数组，便于组件直接使用（每项带 type: 'parameter'|'alarm'|'level'）
                        item.combinedLogs = []
                        if (item.deviceParameterLogList && item.deviceParameterLogList.length) {
                            item.combinedLogs.push(...item.deviceParameterLogList.map(i => ({ ...i, type: 'parameter' })))
                        }
                        if (item.deviceAlarmLogList && item.deviceAlarmLogList.length) {
                            item.combinedLogs.push(...item.deviceAlarmLogList.map(i => ({ ...i, type: 'alarm' })))
                        }
                        if (item.deviceLevelLogList && item.deviceLevelLogList.length) {
                            item.combinedLogs.push(...item.deviceLevelLogList.map(i => ({ ...i, type: 'level' })))
                        }
                    })
                }

            })
        },
        /** 查询对比列表 */
        getCompareList(row) {
            let api
            if (this.activeName === '1') api = paramLogCompareApi
            else if (this.activeName === '2') api = alarmLogCompareApi
            else api = levelLogCompareApi

            api({ id: row.id, deviceId: row.deviceId })
                .then(response => {
                    console.log(response, 'response-对比列表')

                    // 1) 如果后端直接返回了 before/now（对象或字符串），直接赋值并解析由 computed 处理
                    if (response && (response.before !== undefined || response.now !== undefined)) {
                        this.compareInfo = response
                        this.drawer = true
                        return
                    }

                    // 2) 如果后端返回的是字符串形式的两个 JSON 拼接（edge case）
                    if (typeof response === 'string') {
                        try {
                            // 最常见：两个 JSON 用空格或换行分开，尝试拆分
                            const parts = response.trim().split(/}\s*{/)
                            if (parts.length === 2) {
                                const beforeStr = parts[0] + '}'
                                const nowStr = '{' + parts[1]
                                this.compareInfo = { before: beforeStr, now: nowStr }
                                this.drawer = true
                                return
                            }
                        } catch (e) {
                            console.error('尝试拆分合并字符串失败', e)
                        }
                    }

                    // 3) 兜底：无数据
                    this.compareInfo = { before: {}, now: {} }
                    this.drawer = true
                })
                .catch(err => {
                    console.error('getCompareList 接口错误', err)
                    this.compareInfo = { before: {}, now: {} }
                    this.drawer = true
                })
        },
        open(deviceId) {
            this.queryParams.deviceId = deviceId;
            this.getList();
            this.openDetail = true;
            // this.form = row
        },
        handleClick(e) {
            console.log(e.index, 'e');
            this.getList();
        },
        // 日志对比
        handleViewLog(row) {
            console.log(row);
            this.getCompareList(row);
            this.drawer = true;
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
    padding: 30px 20px 0 20px;
}

::v-deep .el-tabs__content {
    height: 70vh !important;
}

.param-compare {
    padding: 16px;
}

.param-name {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    line-height: 1.4;
}

.param-key {
    font-size: 11px;
    color: #999;
}

.changed {
    color: #d7282f;
    font-weight: bold;
}

.empty {
    text-align: center;
    color: #999;
    padding: 40px 0;
}

.alarm-log {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    background: #fafafa;
    border-radius: 8px;
    padding: 8px 12px;
    max-height: 200px;
    overflow-y: auto;
    font-size: 13px;
    line-height: 1.6;
}

.log-item {
    background: #f7f8fa;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 6px 12px;
    min-width: 140px;
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    color: #333;
    transition: all 0.3s;
    margin: 0 0px 10px 0;

}


.log-key {
    color: #666;
}

.log-key-block {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.log-name {
    color: #666;
}

.log-subkey {
    font-size: 11px;
    color: #999;
    margin-top: 2px;
}

.log-value {
    font-weight: 600;
    color: #333;
}

.log-alert {
    border-color: #f56c6c;
    background-color: #fff0f0;
    color: #d7282f;
}
</style>